package framework.impl;

import framework.api.ReleaseId;
import framework.utils.StringUtils;

import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;

public class ReleaseIdImpl implements ReleaseId {

    private String groupId;
    private String artifactId;
    private String version;
    private String type;

    public ReleaseIdImpl(String groupId, String artifactId, String version) {
        this(groupId, artifactId, version, "jar");
    }

    public ReleaseIdImpl(String groupId, String artifactId, String version, String type) {
        this.groupId = groupId;
        this.artifactId = artifactId;
        this.version = version;
        this.type = type;
    }

    @Override
    public String getGroupId() {
        return groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    @Override
    public String getArtifactId() {
        return artifactId;
    }

    public void setArtifactId(String artifactId) {
        this.artifactId = artifactId;
    }

    @Override
    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public static ReleaseId fromPropertiesString(String path) {
        Properties props = new Properties();
        try {
            props.load(new StringReader(path));
            return getReleaseIdFromProperties(props, path);
        } catch (IOException e) {
            throw new RuntimeException("pom.properties was malformed\n" + path, e);
        }
    }

    private static ReleaseId getReleaseIdFromProperties(Properties props, String path) {
        String groupId = props.getProperty("groupId");
        String artifactId = props.getProperty("artifactId");
        String version = props.getProperty("version");
        if (StringUtils.isEmpty(groupId) || StringUtils.isEmpty(artifactId) || StringUtils.isEmpty(version)) {
            throw new RuntimeException("pom.properties exists but ReleaseId content is malformed\n" + path);
        }
        return new ReleaseIdImpl(groupId, artifactId, version);
    }
}
